from  http.client import HTTPConnection
import hashlib
import urllib.parse, urllib.error
import random
import json

appid = '20180705000183004'
secretKey = 'a0ZIAE6HVCsdPhdR9FFE'


def do_translate(query):
    http_client = None
    myurl = '/api/trans/vip/translate'
    q = query
    from_lang = 'en'
    to_lang = 'zh'
    salt = random.randint(32768, 65536)

    sign = appid + q + str(salt) + secretKey
    sign = hashlib.md5(sign.encode('utf-8')).hexdigest()
    myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(
        q) + '&from=' + from_lang + '&to=' + to_lang + '&salt=' + str(salt) + '&sign=' + sign

    http_client = HTTPConnection('api.fanyi.baidu.com')
    http_client.request('GET', myurl)

    # response是HTTPResponse对象
    response = http_client.getresponse()
    # print(response.read())
    return response.read()


reply=do_translate('apple banana').decode('utf-8')
r_obj=json.loads(reply)
r_list=r_obj['trans_result']
print(r_list[0]['dst'])
